package com.meicet.adapter.adapter

import android.graphics.Canvas
import android.graphics.Rect
import android.view.View
import androidx.annotation.Keep
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView
import com.meicet.adapter.base.TaskLife
import com.meicet.adapter.view.Refreshable
import com.meicet.adapter.view.StatusEntity
import com.meicet.adapter.view.StatusListener
import com.meicet.adapter.view.StatusUIState
import com.meicet.adapter.view.StatusView

/**
 * 下拉刷新的adapter  通过父类获取对像配置
 */
@Keep
abstract class BaseRefreshAdapter<T>(@LayoutRes layoutID: Int = 0, list: MutableList<T>? = null) :
    BaseQuickAdapter2<T, BaseHolder>(layoutID, list) {
    // 网络请求生命周期管理
    var statusView: StatusListener? = null
    var statusEntity: StatusEntity? = null
    var refreshableUI: Refreshable? = null
    private var useStateView = true
    private var emptyClickEnable = false
    private var statusUI = StatusUIState.Content
    private var statusUITip = ""

    // 启用装饰器
    private var enableDecoration = true
    var isAttached = false
    fun closeDecorationOffset() {
        enableDecoration = false
    }

    fun closeStateView() {
        useStateView = false
    }

    fun openEmptyClick() {
        emptyClickEnable = true
    }


    open fun onStartLoad(clear: Boolean = false) {
        if (clear) { // 有数据时会清空显示出来loading
            setList(null)
        }
        statusView?.showLoading()
    }

    open fun onStopLoad(error: Boolean = false, msg: String = "") {
        if (data.isEmpty()) {
            if (error) {
                statusView?.showError(msg)
            } else {
                statusView?.showEmpty()
            }
        }
    }

    // 请求刷新回调接口
    abstract fun onPullRefresh()

    // 空布局时点击事件
    open fun onStatusViewClick(isEmpty: Boolean) {
        if (isEmpty) {
            if (emptyClickEnable) {
                onPullRefresh()
            }
        } else {
            onPullRefresh()
        }
    }

    fun onStatusViewState(state: StatusUIState, tip: String = "") {
        this.statusUI = state
        this.statusUITip = tip
        when (state) {
            StatusUIState.Loading -> statusView?.showLoading(tip)
            StatusUIState.Error -> statusView?.showError(tip)
            StatusUIState.Empty -> statusView?.showEmpty(tip)
            StatusUIState.Content -> statusView?.showContent()
        }
    }

    // 重制空状态
    protected open fun onStatusViewAttach() {
        if (useStateView) {
            val stateView = StatusView(context)
            statusEntity?.let {
                stateView.setEmptyText(it.empty)
                stateView.setErrorText(it.error)
                stateView.setLoadText(it.loading)
            }
            setEmptyStatus(stateView)
            onStatusViewSetup(stateView)
            onStatusViewState(statusUI, statusUITip)
        }
    }

    // 配置状态view
    protected open fun onStatusViewSetup(statusView: StatusView) {
    }

    // 装饰器配置 不包含head
    open fun onItemOffsetsRect(outRect: Rect, adapterPosition: Int) {
    }

    // 完成下拉刷新请求  或者 错误重试
    protected fun onRefreshFinish() {
        refreshableUI?.finishRefresh()
    }


    fun setEmptyStatus(view: StatusListener) {
        useStateView = true
        setEmptyView(view.getStatusView())
        statusView = view
        view.setCallBackStatus(object : StatusListener.OnCallBackStatus {
            override fun onClickError(isEmpty: Boolean) {
                onStatusViewClick(isEmpty)
            }
        })
    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        isAttached = true
        onStatusViewAttach()
        val refresh = recyclerView.parent ?: return
        if (refresh is Refreshable) {
            refreshableUI = refresh
            refreshableUI?.setOnRefresh(object : Refreshable.CallBack {
                override fun onRefresh() {
                    onPullRefresh()
                }
            })
        }
        if (enableDecoration) {
            recyclerView.addItemDecoration(itemDecorationOffset)
        }
    }

    override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
        isAttached = false
        refreshableUI?.setOnRefresh(null)
        if (enableDecoration) {
            recyclerView.removeItemDecoration(itemDecorationOffset)
        }
        super.onDetachedFromRecyclerView(recyclerView)
    }

    private val itemDecorationOffset by lazy {
        object : RecyclerView.ItemDecoration() {
            // onDraw：在item绘制之前时被调用，将指定的内容绘制到item view内容之下；
            override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
                super.onDraw(c, parent, state)
            }

            // onDrawOver：在item被绘制之后调用，将指定的内容绘制到item view内容之上
            override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
                super.onDrawOver(c, parent, state)
            }

            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)
                val position = parent.getChildAdapterPosition(view) - headerLayoutCount
                if (position > -1 && data.isNotEmpty()) {
                    onItemOffsetsRect(outRect, position)
                }
            }
        }
    }

}
